from django.core.management.base import BaseCommand
import requests
import time
from apps.flowers.models import Flower
from common.utils.oss_utils import FileOss


class Command(BaseCommand):
    help = '上传鲜花图片到OSS'

    def add_arguments(self, parser):
        parser.add_argument(
            '--force',
            action='store_true',
            help='强制重新上传所有图片',
        )

    def handle(self, *args, **options):
        force = options['force']
        
        # 鲜花图片URL映射
        flower_image_urls = {
            "红玫瑰花束": "https://images.unsplash.com/photo-1518895949257-7621c3c786d7?w=800&h=600&fit=crop",
            "粉玫瑰花束": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
            "白玫瑰花束": "https://images.unsplash.com/photo-1582794543139-8ac9cb0f7b11?w=800&h=600&fit=crop",
            "红康乃馨花束": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
            "粉康乃馨花束": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
            "白百合花束": "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
            "粉百合花束": "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
            "向日葵花束": "https://images.unsplash.com/photo-1470509037663-253afd7f0f51?w=800&h=600&fit=crop",
            "红郁金香花束": "https://images.unsplash.com/photo-1520637836862-4d197d17c93a?w=800&h=600&fit=crop",
            "粉郁金香花束": "https://images.unsplash.com/photo-1584464491033-06628f3a6b7b?w=800&h=600&fit=crop",
            "满天星花束": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop"
        }
        
        oss_client = FileOss()
        self.stdout.write("开始上传鲜花图片到OSS...")
        
        success_count = 0
        error_count = 0
        
        for flower_name, image_url in flower_image_urls.items():
            try:
                # 查找对应的鲜花
                flower = Flower.objects.filter(name=flower_name).first()
                if not flower:
                    self.stdout.write(f"未找到鲜花: {flower_name}")
                    error_count += 1
                    continue
                
                # 检查是否已有图片
                if flower.image and not force:
                    self.stdout.write(f"跳过已有图片: {flower_name}")
                    continue
                
                # 下载图片
                headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                }
                response = requests.get(image_url, headers=headers, timeout=10)
                response.raise_for_status()
                
                # 生成OSS路径
                filename = f"{flower_name}.jpg"
                oss_path = f"flowers/{filename}"
                
                # 上传到OSS
                oss_url = oss_client.get_oss_image_url(oss_path, response.content)
                
                if oss_url:
                    # 直接更新鲜花的image字段
                    flower.image = oss_url
                    flower.save()
                    
                    self.stdout.write(f"✓ 上传成功: {flower_name} -> {oss_url}")
                    success_count += 1
                else:
                    self.stdout.write(f"✗ 上传失败: {flower_name}")
                    error_count += 1
                
                # 添加延迟避免被限制
                time.sleep(1)
                
            except Exception as e:
                self.stdout.write(f"✗ 处理失败 {flower_name}: {e}")
                error_count += 1
        
        self.stdout.write(f"\n上传完成！成功: {success_count}, 失败: {error_count}")